﻿namespace SimpleX.RBAC
{
    public class RelationService : DbRepository<SysRelation>, IRelationService
    {
        public async Task SaveRelationBatch(string category, string objectId, List<string> targetIds, List<string> extJsons, bool clear)
        {
            var sysRelations = new List<SysRelation>();//要添加的列表
            for (int i = 0; i < targetIds.Count; i++)
            {
                sysRelations.Add(new SysRelation
                {
                    ObjectId = objectId,
                    TargetId = targetIds[i],
                    Category = category,
                    ExtJson = extJsons == null ? null : extJsons[i]
                });
            }
            //事务
            var result = await itenant.UseTranAsync(async () =>
            {
                if (clear)
                    await DeleteAsync(it => it.ObjectId == objectId && it.Category == category);//删除老的
                await InsertRangeAsync(sysRelations);//添加新的
            });
            if (result.IsSuccess)//如果成功了
            {
            }
            else
            {
                throw result.ErrorException;
            }
        }

        public async Task SaveRelation(string category, string objectId, string targetId, string extJson, bool clear)
        {
            var sysRelation = new SysRelation
            {
                ObjectId = objectId,
                TargetId = targetId,
                Category = category,
                ExtJson = extJson
            };
            //事务
            var result = await itenant.UseTranAsync(async () =>
            {
                if (clear)
                    await DeleteAsync(it => it.ObjectId == objectId && it.Category == category);//删除老的
                await InsertAsync(sysRelation);//添加新的
            });
            if (!result.IsSuccess)//如果成功了
            {
                throw result.ErrorException;
            }
        }

        public async Task<List<SysRelation>> GetRelationListByObjectIdAndCategory(string objectId, string category)
        {
            var sysRelations = await GetRelationByCategory(category);
            var result = sysRelations.Where(it => it.ObjectId == objectId).ToList();//获取关系集合
            return result;
        }

        public async Task<List<SysRelation>> GetRelationByCategory(string category)
        {
            return await base.GetListAsync(it => it.Category == category);
        }
    }
}